package com.lzb.basic.picselect;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import com.blankj.utilcode.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载媒体文件的管理类
 */
public class MediaLoadManager {

    private static final String NOT_GIF_UNKNOWN = "!='image/*'";
    private static final String NOT_GIF = "!='image/gif' AND " + MediaStore.MediaColumns.MIME_TYPE + NOT_GIF_UNKNOWN;

    private static String[] Q_PROJECTION = new String[]{
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.DURATION,
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.WIDTH,
            MediaStore.Files.FileColumns.HEIGHT,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns._ID,
            MediaStore.Files.FileColumns.DATE_ADDED,
            MediaStore.Files.FileColumns.RELATIVE_PATH
    };

    private static String[] PROJECTION = new String[]{
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.DURATION,
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.WIDTH,
            MediaStore.Files.FileColumns.HEIGHT,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns._ID,
            MediaStore.Files.FileColumns.DATE_ADDED,
    };


    private static String[] IMAGE_PROJECTION = new String[]{
            MediaStore.Video.VideoColumns.DATA,
            MediaStore.Video.VideoColumns.DURATION,
            MediaStore.Video.VideoColumns.DISPLAY_NAME,
            MediaStore.Video.VideoColumns.RELATIVE_PATH,
            MediaStore.Video.VideoColumns.MIME_TYPE,
            MediaStore.Video.VideoColumns.WIDTH,
            MediaStore.Video.VideoColumns.HEIGHT,
            MediaStore.Video.VideoColumns.SIZE,
            MediaStore.Video.VideoColumns._ID,
            MediaStore.Video.VideoColumns.DATE_ADDED,
    };

    /**
     * Get pictures or videos
     */
    private static final String[] SELECTION_ALL_ARGS = {
            String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE),
            String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO),
    };


    private static final String[] SELECTION_VIDEO_ARGS = {
            String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
    };


    private static final String[] SELECTION_IMAGE_ARGS = {
            String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE)
    };

    /**
     * All mode conditions
     * 图片排除掉gif
     *
     * @return
     */
    private static String getSelectionArgsForAllMediaCondition(PhotoConfig.Mode mode) {
        if (mode == PhotoConfig.Mode.PHOTO) {
            return "(" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=? AND " +
                    MediaStore.MediaColumns.MIME_TYPE + NOT_GIF + ") AND " + MediaStore.MediaColumns.SIZE + ">0";
        }
        if (mode == PhotoConfig.Mode.VIDEO) {
            return "(" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=? AND " + MediaStore.Video.VideoColumns.DURATION + ">=500 ) " + " AND " + MediaStore.MediaColumns.SIZE + ">0";
        }
        return "(" + "(" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=? AND " + MediaStore.MediaColumns.MIME_TYPE + NOT_GIF + ")"
                + " OR  (" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=? AND " + MediaStore.Video.VideoColumns.DURATION + ">=500 ) " + ")"
                + " AND " + MediaStore.MediaColumns.SIZE + ">0";
    }


    private static String[] getSelectionArgs(PhotoConfig.Mode mode) {
        if (mode == PhotoConfig.Mode.PHOTO) {
            return SELECTION_IMAGE_ARGS;
        }
        if (mode == PhotoConfig.Mode.VIDEO) {
            return SELECTION_VIDEO_ARGS;
        }
        return SELECTION_ALL_ARGS;
    }

    private static boolean isAndroidQ() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    }

    public static List<SelectMediaEntity> loadAllMediaData(Context context, PhotoConfig.Mode mode) {
        List<SelectMediaEntity> selectMediaEntities = new ArrayList<>();
        Cursor cursor = null;
        try {
            ContentResolver cr = context.getContentResolver();
            Uri uri = MediaStore.Files.getContentUri("external");
            String sortOrder = MediaStore.Files.FileColumns._ID + " DESC";
            cursor = cr.query(uri, isAndroidQ() ? Q_PROJECTION : PROJECTION, getSelectionArgsForAllMediaCondition(mode), getSelectionArgs(mode), sortOrder);
            if (cursor != null) {
                int data_path_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[0]);
                int duration_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[1]);
                int nameIndex = cursor.getColumnIndexOrThrow(Q_PROJECTION[2]);
                int mime_type_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[3]);
                int width_Index = cursor.getColumnIndexOrThrow(Q_PROJECTION[4]);
                int height_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[5]);
                int size_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[6]);
                int id_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[7]);
                int dateAddedIndex = cursor.getColumnIndexOrThrow(Q_PROJECTION[8]);
                int relative_path_index = -1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    relative_path_index = cursor.getColumnIndexOrThrow(Q_PROJECTION[9]);
                }
                while (cursor.moveToNext()) {
                    try {
                        String filePath = cursor.getString(data_path_index);
                        String fileName = cursor.getString(nameIndex);
                        long duration = cursor.getLong(duration_index);
                        String relativePath = filePath;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            if (relative_path_index != -1) {
                                relativePath = cursor.getString(relative_path_index);
                            }
                        }
                        String mimeType = cursor.getString(mime_type_index);
                        int width = cursor.getInt(width_Index);
                        int height = cursor.getInt(height_index);
                        long size = cursor.getLong(size_index);
                        int id = cursor.getInt(id_index);
                        int dateAdded = cursor.getInt(dateAddedIndex);

                        SelectMediaEntity selectMediaEntity;
                        if (mimeType.startsWith("video")) {
                            Uri contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
                            selectMediaEntity = new SelectMediaEntity(contentUri.toString(), relativePath, filePath, mimeType,
                                    duration, fileName, size, width, height, dateAdded);
                            selectMediaEntity.setType(MediaType.Type.VIDEO);
                        } else {
                            Uri contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                            selectMediaEntity = new SelectMediaEntity(contentUri.toString(), relativePath, filePath, mimeType,
                                    duration, fileName, size, width, height, dateAdded);
                            selectMediaEntity.setType(MediaType.Type.IMAGE);
                        }
                        selectMediaEntities.add(selectMediaEntity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        } catch (Exception e) {
            LogUtils.e("扫描异常：" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }
        return selectMediaEntities;
    }

    /*public static List<SelectMediaEntity> loadPhotoMediaData(Context context) {
        List<SelectMediaEntity> selectMediaEntities = new ArrayList<>();
        Cursor cursor = null;
        try {
            ContentResolver cr = context.getContentResolver();
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            String sortOrder = MediaStore.Images.ImageColumns._ID + " DESC";
            String selectionMimeType = MediaStore.MediaColumns.SIZE + ">0";
            cursor = cr.query(uri, IMAGE_PROJECTION, selectionMimeType, null, sortOrder);
            if (cursor != null) {
                int data_path_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0]);
                int duration_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1]);
                int nameIndex = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]);

                int relative_path_index = -1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    relative_path_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[3]);
                }
                int mime_type_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[4]);
                int width_Index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[5]);
                int height_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[6]);
                int size_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[7]);
                int id_index = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[8]);
                int dateAddedIndex = cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[9]);
                while (cursor.moveToNext()) {
                    try {
                        String filePath = cursor.getString(data_path_index);
                        String fileName = cursor.getString(nameIndex);
                        long duration = cursor.getLong(duration_index);
                        String relativePath = filePath;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            if (relative_path_index != -1) {
                                relativePath = cursor.getString(relative_path_index);
                            }
                        }
                        String mimeType = cursor.getString(mime_type_index);
                        int width = cursor.getInt(width_Index);
                        int height = cursor.getInt(height_index);
                        long size = cursor.getLong(size_index);
                        int id = cursor.getInt(id_index);
                        int dateAdded = cursor.getInt(dateAddedIndex);
                        Uri contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                        SelectMediaEntity selectMediaEntity = new SelectMediaEntity(contentUri.toString(), relativePath, filePath, mimeType,
                                duration, fileName, size, width, height, dateAdded);
                        selectMediaEntity.setType(MediaType.Type.IMAGE);
                        selectMediaEntities.add(selectMediaEntity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        } catch (Exception e) {
            LogUtils.e("扫描异常：" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }
        return selectMediaEntities;
    }*/

    public static List<SelectMediaEntity> loadPhotoMediaData(Context context) {
        return loadAllMediaData(context, PhotoConfig.Mode.PHOTO);
    }
}
